package io.github.lee.app.unsplash.ui.detail.photo

import android.app.Application
import com.chad.library.adapter.base.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.app.unsplash.repository.UserRepository
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.repository.domain.User
import io.github.lee.app.unsplash.repository.params.Orientation
import io.github.lee.core.vm.BaseRefreshViewModel
import javax.inject.Inject

@HiltViewModel
class PhotoDetailVM @Inject constructor(
    application: Application,
    private val repo: UserRepository
) : BaseRefreshViewModel<Photo>(application) {

    var user: User? = null
    private var page = 1

    override fun onCreateAdapter(): BaseQuickAdapter<Photo, *> =
        PhotoDetailAdapter()

    //===Desc:===============================================================================


    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        if (isRefresh) {
            page = 1
        } else {
            page++
        }
        launchResult(
            {
                repo.userPhotoList(
                    user?.username ?: "", page, 20,
                    orientation = Orientation.Landscape
                )
            }, {
                error()
                page--
            }
        ) {
            if (!it.isSuccess()) {
                if (isRefresh) {
                    error()
                } else {
                    loadMoreFail()
                    page--
                }
                return@launchResult
            }
            val data = it.data
            if (data.isNullOrEmpty()) {
                if (isRefresh) {
                    refreshSuccess()
                } else {
                    loadMoreSuccess(false)
                }
                return@launchResult
            }
            if (isRefresh) {
                submitList(data)
                refreshSuccess()
            } else {
                addAll(data)
                loadMoreSuccess(page <= 3)
            }
        }
    }


}